﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Identity;
using Volo.Abp.Users;
using YaAppoint.Departments;
using YaAppoint.Organizations.UserDepartments;

namespace YaAppoint.Users
{
    [RemoteService(isEnabled: false)]
    public class CurrentUserDepartmentAppService(ICurrentUser currentUser,
                                        IRepository<IdentityUser,Guid> identityUserReponsitory,
                                        IMapper mapper,
                                        IRepository<Department,Guid> repository,
                                        IRepository<UserDepartment, Guid> userDepartmentRepository
    ) : ApplicationService, ICurrentUserDepartmentAppService, ITransientDependency
    {
        private readonly IRepository<IdentityUser,Guid> _identityUserReponsitory = identityUserReponsitory;
        private readonly IRepository<UserDepartment, Guid> _userDepartmentRepository = userDepartmentRepository;
        private readonly ICurrentUser _currentUser = currentUser;
        private readonly IRepository<Department, Guid> _repository= repository;
        private readonly IMapper  _mapper=mapper;

        /// <summary>
        /// 根据用户名获取科室列表
        /// </summary>
        public async Task<List<DepartmentDto>> GetDepartmentsByUserNameAsync(string userName)
        {
            var list= new List<DepartmentDto>();
            var user = await _identityUserReponsitory.FirstOrDefaultAsync(x => x.NormalizedUserName.Equals(userName));
           
            if (user != null)
            {
               var listDepartment = (await _userDepartmentRepository.GetListAsync(x=>x.User.Id==user.Id)).Select(x=>x.Department).ToList();
               list = _mapper.Map<List<Department>, List<DepartmentDto>>(listDepartment);
            }
            return list;
        }

        public Dictionary<string,string> GetCurrentUserDepartment()
        {
            var res = new Dictionary<string, string>();
            res.Add("name", "永安医技预约");
            res.Add("id",null);
            if (_currentUser.IsAuthenticated)
            {
                var department = _currentUser.FindClaimValue("department-name");
                var depId = _currentUser.FindClaimValue("department-id");
                if (!string.IsNullOrEmpty(department)&& !string.IsNullOrEmpty(depId) )
                {
                    res["name"] = department;
                    res["id"]=depId;
                }
            }
            return res;
        }
    }
}
